package com.codedancer.campus.common.core;

import com.auth0.jwt.JWT;
import com.codedancer.campus.common.response.ApiResponse;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 所有api接口的基类
 */
public abstract class BaseApi {
    /**
     * 获取当前的ServletRequest
     *
     * @return
     */
    protected HttpServletRequest servletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 成功返回具体数据的方法
     *
     * @param <T>
     * @param t
     * @return
     */
    protected <T> ApiResponse<T> success(T t) {
        return ApiResponse.<T>success(t);
    }

    /**
     * 成功返回空数据的方法
     *
     * @param <T>
     * @return
     */
    protected <T> ApiResponse<T> success() {
        return success(null);
    }


    /**
     * 获取当前用户登录的Token
     *
     * @return
     */
    private String currentToken() {
        return servletRequest().getHeader("AUTH_TOKEN");
    }

    /**
     * 获取当前登录用户的uuid
     *
     * @return
     */
    protected String currentLoginUuid() {
        String authToken = currentToken();
        return JWT.decode(authToken).getAudience().get(0);
    }
}
